package g_uuid

import (
	"sync/atomic"
	"time"
)

type IDFetcher struct {
	baseID  uint64
	startID uint64
	seed    uint64
}

func newIDFetcher(srvID uint64) *IDFetcher {
	return &IDFetcher{
		baseID:  srvID,
		startID: uint64(time.Now().Unix()),
		seed:    0,
	}
}

func (srv *IDFetcher) FetchTempID() uint64 {
	seed := srv.incSeed()
	id := srv.baseID<<44 | srv.startID<<32 | seed
	return id
}

func (srv *IDFetcher) incSeed() uint64 {
	var n, v uint64
	for {
		v = atomic.LoadUint64(&srv.seed)
		n = v + 1
		if n > 0xFFFFFFFF {
			n = 0
		}
		if atomic.CompareAndSwapUint64(&srv.seed, v, n) {
			break
		}
	}
	return n
}
